package com.hatricks.is.infrastructure.web;

import cn.hutool.core.map.MapUtil;
import com.hatricks.is.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * @packageName: com.glodon.qydata.archive.infrastructure.util
 * @className: RequestUtils
 * @author: yanyh yanyh@glodon.com
 * @date: 2024/1/17 18:18
 * @description: 请求工具类
 */
@Slf4j
public class RequestUtils {
    /**
     * 获取当前请求模型中的request对象
     *
     * @return request对象
     */
    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.info("当前不处于正常的请求响应模型,如果有需要请深copy后手动设置");
            throw new BusinessException("当前不处于正常的请求模型");
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }


    public static HttpServletResponse getHttpServletResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.info("当前不处于正常的请求响应模型,如果有需要请深copy后手动设置");
            throw new BusinessException("当前不处于正常的请求模型");
        }
        return ((ServletRequestAttributes) requestAttributes).getResponse();
    }

    public static Map<String, String> getRequestHeaders() {
        Map<String, String> headerMap = MapUtil.newHashMap();
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                return headerMap;
            }
            HttpServletRequest request = requestAttributes.getRequest();
            Enumeration<String> enumeration = request.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                if ("content-length".equals(key)) {
                    continue;
                }
                String value = request.getHeader(key);
                headerMap.put(key.toLowerCase(), value);
            }
        } catch (Exception e) {
            throw new BusinessException("获取不到当前Headers,异常信息为:[{}]", e.getMessage());
        }
        return headerMap;
    }

}

